package leetCode.solution;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.stream.Stream;

import com.alibaba.fastjson.JSON;

public class TopK {
	
	public static void main(String[] args) {
		System.out.println(JSON.toJSONString(new TopK().topKFrequent(new int[] {1,1,1,1,1,1,1,1,1,1,1,1,3,2,21,41,5,6,54,32,69,5,5,5,6,6,6,6,2,2,1}, 3)));
	}

	public int[] topKFrequent(int[] nums, int k) {
		int[] result = new int[k];
		PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<Map.Entry<Integer, Integer>>((n1,n2)->n2.getValue()-n1.getValue());
		Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		for(Integer num : nums) {
			map.compute(num, (t,v)->v=(v==null?1:v+1));
		}
		map.entrySet().forEach(e->{
			pq.offer(e);
		});
		
		Stream.iterate(0, n->n+1).limit(k).forEach(
				i->result[i]=pq.poll().getKey()
				);
		
		return result;
	}
}
